from cyxmall.settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from celery_tasks.celery_main import app
from django_redis import get_redis_connection
import logging

logger = logging.getLogger(__name__)
EMAIL_KEY = 'email:verification:%s'

@app.task(name='send_email_task')
def send_email_task(email, verification_code, duration):
    try:
        email_format = {
            'subject': 'cyxmall验证码',
            'message': '',
            'html_message': f"""
                <h3>欢迎注册cyxmall</h3>
                <p>您的验证码是：<span style="color: #FF5722">{verification_code}</span></p>
                <p>验证码有效时长为：{duration}秒</p>""",
            'from_email': EMAIL_HOST_USER,
            'recipient_list': [email],
        }
        res_mail = send_mail(**email_format)
    except Exception as e:
        logger.error('验证码邮件发送[异常][email:%s,message:%s]' % (email, e))
    else:
        if res_mail != 1:
            logger.warning('验证码获取[失败][email:%s]' % email)
        else:
            # 将验证码放入Redis数据库
            # 将cache验证码放入Redis
            cache = get_redis_connection(alias='verify_code')  # 获取Redis连接对象
            cache.set(EMAIL_KEY % email, verification_code, duration)
            # redis 0库存放一个数据，设置过期时间60，每发一次邮件，去查看是否有这个数据，如果有，直接返回，不让重复发送
            cache_default = get_redis_connection()  # 获取redis连接对象
            cache_default.set(email, '1', 60)
            logger.info(
                '邮件发送[正常][email:%s verification_code:%s]' %
                (email, verification_code))
